package br.com.treinar.dao;

import java.util.List;
import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
@SuppressWarnings("unchecked")
public abstract class GenericDAO<T, PK> {

	private EntityManager em;

	public GenericDAO(EntityManager em) {
		this.em = em;
	}
	
	public void persist(T object) {
		em.persist(object);
	}
	

	public List<T> selectALL() {
		return em.createQuery("from " + getTypeClass().getClass().getName()).getResultList();
	}
	
	public void remove(T object) {
		em.remove(object);
	}
	
	public T selectById(PK id) {
		return (T) em.find(getTypeClass(), id);
	}
	
	public void update(T object) {
		em.merge(object);
	}
	
	private Class<?> getTypeClass() {
        Class<?> clazz = (Class<?>) ((ParameterizedType) this.getClass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
        return clazz;
    }
	
}
